export const formatTime = (time, fmt) => {
  if (!time) return "";
  const date = new Date(time);
  const o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds(),
  };
  const re = /(y+)/;
  if (re.test(fmt)) {
    const t = re.exec(fmt)[1];
    fmt = fmt.replace(
      t,
      (date.getFullYear() + "").substring(4 - t.length)
    );
  }
  for (let k in o) {
    const regx = new RegExp("(" + k + ")");
    if (regx.test(fmt)) {
      const t = regx.exec(fmt)[1];
      fmt = fmt.replace(
        t,
        t.length == 1 ? o[k] : ("00" + o[k]).substring(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

export const resize = (chart) => {
  let timer = 0;

  window.addEventListener("resize", () => {
    clearTimeout(timer);

    timer = setTimeout(() => {
      chart.resize();
    }, 300);
  });
};

// video视频图片保存
export const videoScreenImageSave = (video, name) => {
  // 第一步
  // 创建canvas元素
  const canvas = document.createElement("canvas");
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  // 获取canvas的上下文
  const ctx = canvas.getContext("2d");
  // 绘制当前视频帧到canvas上
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  // 将canvas转换为Base64图片格式
  const dataUrl = canvas.toDataURL("image/png");

  //第二步： 先转成blob格式
  let arr = dataUrl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    byte = atob(arr[1]),
    n = byte.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = byte.charCodeAt(n);
  }
  const src = new Blob([u8arr], { type: mime })
  //第三步： 保存图片至本地
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(src, name);
  } else {
    const link = document.createElement("a");
    link.setAttribute("href", window.URL.createObjectURL(src));
    link.setAttribute("download", name);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}